package cn.innosmart.aq.bean;

import android.os.Parcel;
import android.os.Parcelable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;

/**
 * Created by David on 2015/7/29.
 */
public class DeviceBean implements Parcelable {
    public static final Parcelable.Creator<DeviceBean> CREATOR = new Parcelable.Creator<DeviceBean>() {
        public DeviceBean createFromParcel(Parcel source) {
            return new DeviceBean(source);
        }

        public DeviceBean[] newArray(int size) {
            return new DeviceBean[size];
        }
    };
    private String devicetype;
    private int functype;
    private int sensorunit;
    private double sensorvalue;
    private boolean sensorValueIsSet = false;
    //    private double basicvalue;
    private String name;
    private String place;
    private String label;
    private int nodeid;
    private String address;
    private String homeid;
    private String deviceid;
    private boolean alarm;
    private String userTag;
    //严重报警的判断标志
    private boolean deepAlarm;
    private int commandid;
    private int index;

    private long ts;

    public int getRebootValue() {
        return reboot_value;
    }

    private int reboot_value;

    public volatile boolean newMeterValueGot = true;

    public boolean getNewMeterValueGot() {
        mutex.lock();
        boolean ret = newMeterValueGot;
        mutex.unlock();
        return ret;
    }

    public void setNewMeterValueGot(boolean bv) {
        mutex.lock();
        newMeterValueGot = bv;
        mutex.unlock();
    }

    public DeviceBean() {
        ts = System.currentTimeMillis();
    }

    public boolean isSensorValueIsSet() {
        return sensorValueIsSet;
    }

    public DeviceBean(JSONObject jsonDevice) {
        ts = System.currentTimeMillis();

        try {
            this.devicetype = jsonDevice.getString("devicetype");
            this.functype = jsonDevice.getInt("functype");
            try {
                this.sensorunit = jsonDevice.getInt("sensorunit");
            } catch (JSONException e) {
            }


            try {
                this.label = jsonDevice.getString("label");
            } catch (JSONException e) {
            }

            try {
                this.userTag = jsonDevice.getString("user_tag");
            } catch (JSONException e) {
//                e.printStackTrace();
            }
            try {
                this.name = jsonDevice.getString("name");
            } catch (JSONException e) {
//                e.printStackTrace();
            }
            try {
                this.place = jsonDevice.getString("place");
            } catch (JSONException e) {
            }
            //"address":"zwave://da887909/17/49/1/23"
            this.address = jsonDevice.getString("address");
            try {
                this.deviceid = jsonDevice.getString("id");
            } catch (JSONException e) {
            }

            try {
                this.setSensorvalue(jsonDevice.getDouble("sensorvalue"));
            } catch (JSONException e) {
            }


            String[] rootArray = address.split("//");
            String[] dataArray = rootArray[1].split("/");
            try {
                this.homeid = dataArray[0];
                this.nodeid = Integer.valueOf(dataArray[1]);
                this.commandid = Integer.valueOf(dataArray[2]);
                this.index = Integer.valueOf(dataArray[3]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (address.contains("webbus")) {
                this.place = "SN0521_AAAAAAAAAAAAAAAAAAAA";
                for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
                    if ("SN0521_AAAAAAAAAAAAAAAAAAAA".equals(SystemConstant.aquariumList.get(i).getId())) {
                        SystemConstant.aquariumList.get(i).getDeivices().add(address);
                    }
                }
            }
            if (functype == DeviceConstant.FUNCTYPE_WATERLEVER) {
                if (sensorvalue != 0) {
                    setAlarm(true);
                } else {
                    setAlarm(false);
                }
            }

            if (functype == DeviceConstant.FUNCTYPE_SWITCH) {
                try {
                    this.reboot_value = jsonDevice.getInt("reboot_value");
                } catch (JSONException e) {
                    this.reboot_value = -1;
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    protected DeviceBean(Parcel in) {
        this.devicetype = in.readString();
        this.functype = in.readInt();
        this.sensorunit = in.readInt();
        this.sensorvalue = in.readDouble();
        this.name = in.readString();
        this.place = in.readString();
        this.label = in.readString();
        this.nodeid = in.readInt();
        this.address = in.readString();
        this.homeid = in.readString();
        this.deviceid = in.readString();
        this.alarm = in.readByte() != 0;
        this.userTag = in.readString();
        this.commandid = in.readInt();
        this.index = in.readInt();

        ts = System.currentTimeMillis();

    }

    public boolean isDeepAlarm() {
        return deepAlarm;
    }

    public void setDeepAlarm(boolean deepAlarm) {
        this.deepAlarm = deepAlarm;
    }

    public String getUserTag() {
        return userTag;
    }

    public void setUserTag(String userTag) {
        this.userTag = userTag;
    }

    public boolean isAlarm() {
        return alarm;
    }

    public void setAlarm(boolean alarm) {
        this.alarm = alarm;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public String getDeviceid() {
        return deviceid;
    }

    public void setDeviceid(String deviceid) {
        this.deviceid = deviceid;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDevicetype() {
        return devicetype;
    }

    public void setDevicetype(String devicetype) {
        this.devicetype = devicetype;
    }

    public int getFunctype() {
        return functype;
    }

    public void setFunctype(int functype) {
        this.functype = functype;
    }

    public int getSensorunit() {
        return sensorunit;
    }

    public void setSensorunit(int sensorunit) {
        this.sensorunit = sensorunit;
    }

    public double getSensorvalue() {
        double ret;
        mutex.lock();
        ret = sensorvalue;
        mutex.unlock();
        return ret;
    }

    private Lock mutex = new ReentrantLock(true);

    public int oldAlarmType = -1;

    private TimerTask offlineSetTask;

    public void setSensorvalue(final double sensorvalue) {
        mutex.lock();
        System.out.println("setSensorvalue " + this.address + ", name:" + this.name);

        this.sensorValueIsSet = true;
        this.sensorvalue = sensorvalue;
        this.newMeterValueGot = true;
        ts = System.currentTimeMillis();

        if (offlineSetTask != null) {
            offlineSetTask.cancel();
        }
        offlineSetTask = new TimerTask() {
            @Override
            public void run() {
                System.out.println(name + "set to null," + address);
                sensorValueIsSet = false;
            }
        };
        Timer timer = new Timer();
        timer.schedule(offlineSetTask, 6 * 60 * 1000);

        mutex.unlock();
    }

    public long getTS() {
        return ts;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPlace() {
        return place;
    }

    public void setPlace(String place) {
        this.place = place;
    }

    public int getNodeid() {
        return nodeid;
    }

    public void setNodeid(int nodeid) {
        this.nodeid = nodeid;
    }

    public String getHomeid() {
        return homeid;
    }

    public void setHomeid(String homeid) {
        this.homeid = homeid;
    }

    public int getCommandid() {
        return commandid;
    }

    public void setCommandid(int commandid) {
        this.commandid = commandid;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    @Override
    public String toString() {
        return "DeviceBean{" +
                "address='" + address + '\'' +
                "devicetype='" + devicetype + '\'' +
                ", functype=" + functype +
                ", sensorunit=" + sensorunit +
                ", sensorvalue=" + sensorvalue +
                ", name='" + name + '\'' +
                ", place='" + place + '\'' +
                ", nodeid=" + nodeid +
                ", homeid=" + homeid +
                ", commandid=" + commandid +
                ", index=" + index +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.devicetype);
        dest.writeInt(this.functype);
        dest.writeInt(this.sensorunit);
        dest.writeDouble(this.sensorvalue);
        dest.writeString(this.name);
        dest.writeString(this.place);
        dest.writeString(this.label);
        dest.writeInt(this.nodeid);
        dest.writeString(this.address);
        dest.writeString(this.homeid);
        dest.writeString(this.deviceid);
        dest.writeByte(alarm ? (byte) 1 : (byte) 0);
        dest.writeString(this.userTag);
        dest.writeInt(this.commandid);
        dest.writeInt(this.index);
    }

    public void setRebootValue(int rebootValue) {
        this.reboot_value = rebootValue;
    }
//
//    public class DelaySetRunnable implements Runnable {
//        private double value = 0;
//        private int delay = 0;
//
//        public DelaySetRunnable(double value, int delay) {
//            this.value = value;
//            this.delay = delay;
//        }
//
//        @Override
//        public void run() {
//            try {
//                Thread.sleep(delay);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//
//            System.out.println("----------> delay set");
//            setSensorvalue(this.value);
//        }
//    }
//
//    private Thread td1 = null;
//
//    public void setSensorvalueDelay(Double sensorvalue, int delay) {
//        DelaySetRunnable sr1 = new DelaySetRunnable(sensorvalue, delay);
//        if (td1 != null) {
//            td1.interrupt();
//            td1 = null;
//        }
//
//        td1 = new Thread(sr1, "sr1");
//        td1.start();
//    }
}
